<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\BaseController;
use app\common\model\content\Image;
use app\admin\traits\UploadImage;
use app\common\model\content\Category as CategoryModel;
use app\common\model\content\ArticleForm;
use app\common\validate\Article as ArticleValidate;
use app\common\validate\Image as ImageValidate;
use think\Exception;
use app\common\model\content\Article as ArticleModel;
use think\facade\Filesystem;
use think\facade\Log;
use app\common\model\content\Topic as TopicModel;
use app\common\components\Purifier;

class Article extends BaseController
{
    //是否关联user模型( 用于权限规则验证 )
    public $relateUser = true;

    use UploadImage;

    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['list','save','update','delete', 'status','disallow','batchTrash','uploadArticleImage','articleImage']],
    ];

    private $_model = null;

    /**
     * 上传文章图片
     * @return \think\response\Json
     */
    public function uploadArticleImage(){
        return $this->upload(
            ArticleModel::UP_FIELD,
            ArticleModel::UP_FOLDER,
            ['width'=>479, 'height'=>204]
            );
    }

    //上传文章内容图片
    public function articleImage(){
        try{

            $files = request()->file();
            if (empty($files)) throw new Exception('没有选择任何图片.');
            validate(ImageValidate::class)->check($files);

            if( !$rel = Filesystem::disk('public')->putFile( Image::TMP_PATH, $files[Image::FIELD_NAME]) )
                throw new Exception('上传文件失败.');

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg'  => $e->getMessage(),
            ]);
        }

        return json([
            'code' => 0,
            'msg'  => '上传成功.',
            'data' => [
                'src' => config('filesystem.disks.public.url') . '/' . str_replace('\\','/', $rel)
            ]
        ]);

    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return view('article/index', array(
            'category' => CategoryModel::getDropList(),
            'status' => array(
                ArticleModel::STATUS_PUB => '已发布',
                ArticleModel::STATUS_DRA => '草稿箱',
                ArticleModel::STATUS_TRA => '回收站'
            )
        ));
    }


    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return view('article/create',[
            'category' => CategoryModel::getDropList()
        ]);
    }

    //创建话题文章(必须传递话题id)
    public function topicCreate(int $topic_id)
    {
        return view('article/topic_create',[
            'topicModel' => $this->getModel(TopicModel::class, $topic_id),
        ]);
    }

    /**
     * 保存新建的资源
     * @return \think\Response
     */
    public function save()
    {
        if(!request()->isPost()) return redirect((string) url('/'));

        $model = $this->getFormModel();
        if (request()->has('topic_id')){
            $model->scene = ArticleModel::SCENE_TOPIC;
        }

        return $this->saveArticle($model);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(int $id)
    {
        return view('article/edit',[
            'category' => CategoryModel::getDropList(),
            'model' => $this->getFormModel($id)->getModel(),
            'empty_image' => config('app.empty_image')
        ]);
    }
    //修改话题文章
    public function topicEdit(int $topic_id, int $id)
    {
        return view('article/topic_edit',[
            'topicModel' => $this->getModel(TopicModel::class, $topic_id),
            'model'  => $this->getFormModel($id)->getModel(),
            'empty_image' => config('app.empty_image')
        ]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(int $id)
    {
        if(!request()->isPost()) return redirect((string) url('/'));

        $model = $this->getFormModel($id);
        if (request()->has('topic_id')){
            $model->scene = ArticleModel::SCENE_TOPIC;
        }

        return $this->saveArticle($model);
    }

    /**
     * #文章保存操作
     * @param ArticleForm $model
     * @return \think\response\Json
     */
    private function saveArticle(ArticleForm $model){
        try{
            //验证数据
            $data = request()->only(['title','topic_id','brief','category_id','image','disallow','tags','status','best']);

            //xss过滤
            $data['content'] = (new Purifier())->filter(input('content', '', null));

            validate(ArticleValidate::class)->scene($model->scene)->check($data);

            $data['disallow'] = isset($data['disallow']) && $data['disallow'] == 0 ? '0' : '1';
            //截取文章内容
            $data['brief'] = $data['brief'] ?: truncate_utf8_string(cutstr_html($data['content']), ArticleForm::BRIEF_LEN, '');

            //保存数据
            $model->store($data);

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
        return json(['code'=>0, 'msg'=>'保存文章成功.']);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(int $id)
    {
        

        try{
            //获取模型
            $model = $this->getFormModel($id)->getModel();

            //判断话题是否完结
            $topic = $model->topic;
            if($topic && $topic->status === TopicModel::DONE_YES){
                throw new Exception('话题完结,禁止操作.');
            }
        

            if ($model->together(['content'])->delete() === false){
                throw new Exception('删除文章失败.');
            }

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
        //删除成功
        return json(['code'=>0,'msg'=>'删除文章成功']);

    }

    /**
     * #批量放入回收站
     * @return array
     */
    public function batchTrash(){
        try{
            //获取话题id
            $topic_id = input('tid/d');
            if ($topic_id > 0) {
                //查看话题是否完结
                $topic = $this->getModel(TopicModel::class, $topic_id);
                if ($topic && $topic->status === TopicModel::DONE_YES) {
                    throw new Exception('话题完结,禁止操作.');
                }
            }

            $ids = explode(',', trim(request()->param('ids'),','));

            if($this->batchRule(ArticleModel::class, (array) $ids) &&
                ArticleModel::update(['status'=>ArticleModel::STATUS_TRA], ['id'=>$ids]) === false
            ){
                throw new Exception('批量放置回收站失败.');
            }
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }

        return json([
            'code' => 0,
            'msg' => '批量放置回收站成功.'
        ]);
    }

    /**
     * 改变可评论状态
     */
    public function disallow(int $id){
        try{
            $model = $this->getFormModel($id)->getModel();
            $model->disallow = input('value/s');
            if ($model->save() === false) throw new Exception('操作失败.');

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
        return json(['code'=>0,'msg'=>'操作成功.']);
    }



    /**
     * 文章列表(table数据)
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function list()
    {

        try{
            //获取列表数据
            $data = ArticleModel::getListData($this->ruleWhere());


        }catch (\Exception $e){
            //系统错误
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage(),
            ]);
        }

        //成功返回
        return json([
            'code'  => 0,
            'msg'=> '查询列表成功',
            'count' => $data['count'],
            'data'  => $data['list']
        ]);
    }


    /**
     * 将文章放置回收站 将文章重新发布
     */
    public function status(int $id, int $status){
        try{
            $model = $this->getFormModel($id)->getModel();

            //判断话题是否完结
            $topic = $model->topic;
            if($topic && $topic->status === TopicModel::DONE_YES){
                throw new Exception('话题完结,禁止操作.');
            }


            $model->status = $status;
            if ( $model->save() === false ) throw new Exception('改变状态失败.');

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
        return json(['code'=>0,'msg'=>'改变状态成功.']);
    }

    /**
     * 获取模型
     * @param int $id
     * @return ArticleForm
     * @throws
     */
    protected function getFormModel(int $id = null){
        if ( ! $this->_model instanceof ArticleForm ){
            $model = new ArticleForm();

            if ( is_null($id) )
                $model->setModel($this->getModel(ArticleModel::class));
            else
                $model->setModel($this->getModel(ArticleModel::class, $id, ['content']));

            $this->_model = $model;
        }
        return $this->_model;
    }


}
